<template>
  <div>
    <FormPanel ref="topForm" :list="topFilterList" :cols="3" labelWidth="120" :isSubmitBtn="false" @filterChange="changeHandle" @onCollapse="collapseHandle"></FormPanel>
    <div class="searchBtn">
      <AjaxButton type="primary" :click="handleLocalQuery">本地查询</AjaxButton>
      <AjaxButton type="primary" :click="handleRealeTimeQuery">实时查询</AjaxButton>
      <AjaxButton :click="handleReset">重置</AjaxButton>
    </div>
    <FilterTable
      ref="table"
      columnsRef="part_report_orderExecution_main"
      :columns="columns"
      :isMemoryPagination="true"
      :onColumnsChange="columns => (this.columns = columns)"
      :isSelectColumn="true"
      selectionType="single"
      :dataSource="dataSource"
      :onSyncTableData="tableHandle"
      :onRowSelectChange="e => (this.selectedRow = e)"
      :isExportExcel="true"
      :onCalcExportData="exportFun"
      exportFileName="查询订单执行情况.xlsx"
    >
      <!-- :fetchapi="fetchApi"
      :params="fetchParams" -->
      <!-- <template slot="moreActions">
        <span @click="removeRecordHandle">删除数据</span>
      </template> -->
      <template slot="controls">
        <!-- <el-button size="small" type="primary" @click="addRecordHandle">到货确认</el-button>-->
        <el-button size="small" type="primary" @click="handleSign">签收</el-button>
        <el-button size="small" :loading="printBtnLoading" icon="el-icon-printer" type="primary" @click="handleApplyPrint">打印申请单</el-button>
        <el-button size="small" type="primary" icon="el-icon-printer" @click="handleDeliverPrint">打印发货单</el-button>
      </template>
    </FilterTable>
    <!-- 到货确认 -->
    <BaseDialog :visible.sync="visibleArrival" title="到货确认信息" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <arrival type="edit" :modifyType="modifyType" :rowData="formData" @onConfirm="handlerSelectConfirm" @close="closeHandler" />
    </BaseDialog>
    <!-- 明细 -->
    <BaseDialog :visible.sync="visibleItem" title="订货申请单明细" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <item :rowData="itemData" :orderTypeData="orderSelectData" :shippedDict="shippedDict" @close="() => (this.visibleItem = false)" />
    </BaseDialog>
    <!-- 发货单 -->
    <BaseDialog :visible.sync="visibleShipped" title="发货单明细" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <shippedOrder :rowData="itemData" @close="() => (this.visibleShipped = false)" />
    </BaseDialog>
    <!-- 发票 -->
    <BaseDialog :visible.sync="visibleInvoice" title="发票明细" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <invoice :rowData="itemData" @close="() => (this.visibleInvoice = false)" />
    </BaseDialog>
    <!-- 欠货单 -->
    <BaseDialog :visible.sync="visibleBackorder" title="欠货单" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <backorder :rowData="itemData" @close="() => (this.visibleBackorder = false)" />
    </BaseDialog>
    <!-- 打印插件 -->
    <BasePrint ref="print" :data="printData" template="part/report/templateOrderExecutionTemplate" />
    <!-- 打印发货单 -->
    <BasePrint ref="printShippedOrder" :data="printShippedOrderList" template="part/report/tempplateShippedOrder" />
    <!-- 关闭按钮 -->
    <div v-if="showClose" class="btnWrap">
      <el-button @click="handlePageClose">关闭</el-button>
    </div>
    <!-- 签收页面 -->
    <BaseDialog :visible.sync="signOfVisible" title="货运单签收" destroyOnClose :containerStyle="{ height: 'calc(100% - 50px)', overflow: 'auto', paddingBottom: '60px' }">
      <editPartOrderSign :id="selectBillId" :billNo="selectedBillNo" @close="signOfVisible = false"></editPartOrderSign>
    </BaseDialog>
  </div>
</template>

<script>
/*
 *
 * 查询订单执行情况报表.
 * 测试的时候 实时的 订货申请单号用 0020265463
 * 本地的 订货申请单号用  0020267028
 * model.setI_WXZ("7580208");
 */

import moment from 'moment';
import { notifyAction } from '@/utils';
import { authority } from '@/utils/authMixin';
import { getCompanyId } from '@/assets/js/auth';
import { queryOrderInfo, queryLocalOrderInfo, queryOrderSelectInfo, queryOrderPrintData, getShippedItem, getShippedHeader, getShippedDict } from '@/api/part/report/orderExecution';

import { queryCompanyInforById, queryTex, queryAllOrderTypeInfo } from '@/api/part/common';
import arrival from './arrival';
import item from './item';
import shippedOrder from './shippedOrder';
import invoice from './invoice';
import backorder from './backorder';
import editPartOrderSign from '@/pages/part/partInventory/partSign/editPartOrderSign';

export default {
  name: 'inOutReport',
  components: {
    arrival,
    item,
    shippedOrder,
    invoice,
    backorder,
    editPartOrderSign
  },
  mixins: [authority],
  props: {
    showClose: {
      type: Boolean,
      default: false
    },
    ptype: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      modifyType: true,
      visibleArrival: false,
      topFilterList: this.createTopFilters(),
      fetchApi: queryLocalOrderInfo,
      columns: this.createTableColumns(),
      fetchParams: { xhrAbort: true },
      formData: {}, // 向子组件传数据的数组
      tableData: [], // 表单数据
      selectedRow: [], // 选中的行项数据
      printData: {}, // 打印数据
      tax: 0, // 税率
      printBtnLoading: false,
      orderTypeData: {}, // 订单类型数据(翻译用)
      dataSource: [],
      visibleItem: false, // 订货申请单明细
      visibleShipped: false, // 发货单明细
      visibleInvoice: false, // 发票明细
      visibleBackorder: false, // 欠货单
      itemData: [], // 明细上方表单数据
      orderSelectData: [],
      printShippedOrderList: {}, // 发货单

      signOfVisible: false, // 是否显示签收弹框
      selectedBillNo: '', // 选中的订单编号
      selectBillId: '', // 选中的订单id
      shippedDict: [], // 发货点字典
      partOrBoutique: this.ptype ? '精品代码' : '配件代码'
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getlist();
    // 查询发货点
    this.initShippedDict();
    this.topFilterList.find(e => e.fieldName == 'I_MATNR').label = this.partOrBoutique;
  },
  methods: {
    async initShippedDict() {
      let res = await getShippedDict();
      // console.log('发货点', res.data);
      this.shippedDict = res.data.map(e => ({ text: e.SHIPPED_POINT_NAME, value: e.SHIPPED_POINT_CODE + '' }));
      this.columns.forEach(element => {
        switch (element.dataIndex) {
          case 'VSTEL':
            element.dictItems = this.shippedDict;
            element.filterItems = this.shippedDict;
            break;
          default:
            break;
        }
      });
    },
    exportFun(row) {
      for (const key in row) {
        switch (key) {
          case 'ADJUST_DATE':
            if (row[key]) {
              row[key] = moment(row[key]).format('YYYY-MM-DD');
            }
            break;
          case 'CONSULTANT':
            if (row[key]) {
              row[key] = this.userList[row[key]];
            }
            break;
          case 'STOCK_QUANTITY':
          case 'OUT_PRICE':
          case 'COST_PRICE':
          case 'OUT_AMOUNT':
          case 'COST_AMOUNT':
            if (row[key]) {
              row[key] = Number(row[key]).toFixed(2);
            }
            break;
          case 'QAUART':
            row[key] = row[key] == 'QT' ? '正常订单' : this.orderTypeData[row[key]] || params.row.QAUART;
            break;
          case 'QCFM':
            row[key] = row[key] == 'X' ? '已确认' : row[key] == 'N' ? '未确认' : row[key];
            break;
          case 'QFLAG':
            let statusName = '';
            switch (row[key]) {
              case 'X':
                statusName = '紧急';
                break;
              case 'Y':
                statusName = '紧急';
                break;
              case '':
                statusName = '正常';
                break;
            }
            row[key] = statusName;
            break;
          default:
            break;
        }
      }
    },
    // 打印
    async handleDeliverPrint() {
      if (!this.selectedRow || !this.selectedRow.length) {
        return this.$notify.warning({ title: '提示信息', message: '请选中一条数据' });
      }
      let res = await getShippedItem({
        I_DVBELN: this.selectedRow[0].DVBELN,
        I_SVBELN: this.selectedRow[0].SVBELN
      });
      let headerRes = await getShippedHeader({ I_DVBELN: this.selectedRow[0].DVBELN, I_SVBELN: this.selectedRow[0].SVBELN });
      this.printShippedOrderList.baseInfo = headerRes.data[0];
      this.printShippedOrderList.saleNo = this.selectedRow[0].SVBELN;
      this.printShippedOrderList.itemlist = res.data;
      // console.log(res.data, '发货单数据', '打印数据', this.printShippedOrderList);
      this.$refs.printShippedOrder.EXCUTE_PRINT();
    },
    // 明细按钮
    itemHandle(val) {
      this.itemData = val;
      // console.log(this.itemData, 1231);
      this.visibleItem = true;
    },
    // 发货单
    shippedHandle(val) {
      this.itemData = val;
      // console.log(this.itemData, 1231);
      this.visibleShipped = true;
    },
    // 发票
    saleInvoiceHandle(val) {
      this.itemData = val;
      // console.log(this.itemData, 1231);
      this.visibleInvoice = true;
    },
    // 发票
    backorderHandle(val) {
      this.itemData = val;
      // console.log(this.itemData, 1231);
      this.visibleBackorder = true;
    },
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '订货申请单号',
          fieldName: 'I_QVBELN'
        },
        {
          type: 'INPUT',
          label: '发货清单号',
          fieldName: 'I_DVBELN'
        },
        {
          type: 'RANGE_DATE',
          label: '订货申请单日期',
          dateType: 'daterange',
          style: { minWidth: '120px' },
          initialValue: [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
          fieldName: 'I_QERDATS|I_QERDARE'
        },
        {
          type: 'RANGE_DATE',
          label: '发货清单日期',
          dateType: 'daterange',
          style: { minWidth: '120px' },
          fieldName: 'I_DERDATS|I_DERDARE'
        },
        {
          type: 'INPUT',
          label: '销售订单号',
          fieldName: 'I_SVBELN'
        },
        {
          type: 'RANGE_DATE',
          label: '销售订单日期 ',
          dateType: 'daterange',
          style: { minWidth: '180px' },
          fieldName: 'I_SERDATS|I_SERDARE'
        },
        {
          type: 'INPUT',
          label: '采购订单号',
          fieldName: 'I_PONUM'
        },
        {
          type: 'SELECT',
          label: '订单性质',
          fieldName: 'I_FLAG',
          itemList: [
            { text: '全部', value: '' },
            { text: '紧急', value: 'X' },
            { text: '正常', value: 'N' }
          ]
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'I_AUART',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'I_MATNR'
        },
        {
          type: 'SELECT',
          label: '到货确认',
          fieldName: 'I_DHQR',
          itemList: [
            { text: '全部', value: '' },
            { text: '已确认', value: 'X' },
            { text: '未确认', value: 'N' }
          ]
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          width: 220,
          // sorter: true,
          disabled: true,
          render: props => {
            return (
              <div>
                <el-button type="text" size="mini" onClick={() => this.itemHandle(props.row)}>
                  明细
                </el-button>
                <el-button type="text" size="mini" onClick={() => this.shippedHandle(props.row)}>
                  发货单
                </el-button>
                <el-button type="text" size="mini" onClick={() => this.saleInvoiceHandle(props.row)}>
                  销售发票
                </el-button>
                <el-button type="text" size="mini" onClick={() => this.backorderHandle(props.row)}>
                  欠货单
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          // fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '订货申请单号',
          dataIndex: 'QVBELN',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '有效期天数',
          dataIndex: 'YXDAYS',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '建立人',
          dataIndex: 'QERNAM',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '建立日期',
          dataIndex: 'QERDAT',
          align: 'center',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '需求单类型',
          dataIndex: 'QAUART',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: params => {
            return <span>{params.row.QAUART == 'QT' ? '正常订单' : this.orderTypeData[params.row.QAUART] || params.row.QAUART}</span>;
          }
        },
        {
          title: '确认',
          dataIndex: 'QCFM',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: params => {
            let statusName = '';
            switch (params.row.QCFM) {
              case 'X':
                statusName = '已确认';
                break;
              case 'N':
                statusName = '未确认';
                break;
            }
            return <span>{statusName}</span>;
          }
        },
        {
          title: '紧急',
          dataIndex: 'QFLAG',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: params => {
            let statusName = '';
            switch (params.row.QFLAG) {
              case 'X':
                statusName = '紧急';
                break;
              case 'Y':
                statusName = '紧急';
                break;
              case '':
                statusName = '正常';
                break;
            }
            return <span>{statusName}</span>;
          }
        },
        {
          title: '发货单建立日期',
          dataIndex: 'DERDAT',
          align: 'center',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '确认用户',
          dataIndex: 'QCNAM',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '确认日期',
          dataIndex: 'QCDAT',
          align: 'center',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '确认时间',
          dataIndex: 'QCTIM',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '发货单号',
          dataIndex: 'DVBELN',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售订单号',
          dataIndex: 'SVBELN',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售订单建立日期',
          dataIndex: 'SERDAT',
          align: 'center',
          sorter: true,
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '发货点',
          dataIndex: 'VSTEL',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: [],
          showOverflowTooltip: true
        },
        {
          title: '是否发往中转库',
          dataIndex: 'ZZKFLAG',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '出库文本',
          dataIndex: 'DMATDOC',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售发票',
          dataIndex: 'BVBELN',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售发票建立日期',
          dataIndex: 'BERDAT',
          align: 'center',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '客户采购订单号',
          dataIndex: 'DHH',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    // 搜索
    changeHandle(val) {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign(this.fetchParams, { xhrAbort: false }, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    // table动态回调函数
    tableHandle(val) {
      this.tableData = val;
      // console.log(this.tableData);
    },
    addRecordHandle() {
      this.visibleArrival = true;
    },
    // 点击本地查询
    async handleLocalQuery() {
      // console.log('已走本地');
      this.fetchApi = queryLocalOrderInfo;
      // console.log(123);

      this.reSearchLocalTableData();
    },
    // 点击实时查询
    async handleRealeTimeQuery() {
      this.fetchApi = queryOrderInfo;
      this.reSearchTableData();
    },
    // 点击重试
    async handleReset() {
      this.$refs.topForm.RESET_FORM();
      this.reSearchTableData();
    },
    // 重新查询实时主表数据
    async reSearchTableData() {
      let formData = await this.$refs.topForm.GET_FORM_DATA();
      // console.log(formData[1].I_QVBELN, '行啊');
      if (false == formData[0]) {
        this.fetchParams.xhrAbort = true;
        this.fetchParams = Object.assign(this.fetchParams, {
          xhrAbort: false,
          ...formData[1]
        });
      }
      let res = await queryOrderInfo(this.fetchParams);
      this.dataSource = [];
      if (res.data && res.data.length > 0) {
        this.dataSource = res.data;
      }
      // this.BaseTable.CLEAR_EXECUTE_LOG();
      // this.BaseTable.EXECUTE_INSERT(res.data);
    },
    // 重新查询本地主表数据
    async reSearchLocalTableData() {
      // console.log(2);

      let formData = await this.$refs.topForm.GET_FORM_DATA();
      // console.log(formData, 3);

      // 必填表单已填
      if (false == formData[0]) {
        this.fetchParams.xhrAbort = true;
        this.fetchParams = Object.assign(this.fetchParams, {
          xhrAbort: false,
          ...formData[1]
        });
      }
      let res = await queryLocalOrderInfo(this.fetchParams);
      // this.BaseTable.CLEAR_EXECUTE_LOG();
      // this.BaseTable.EXECUTE_INSERT(res.data);
      this.dataSource = [];
      if (res.data && res.data.length > 0) {
        this.dataSource = res.data;
      }
    },
    // 获取订单类型下拉数据.
    async getlist() {
      this.orderSelectData = (await queryOrderSelectInfo()).data;
      // console.log(this.orderSelectData, '下拉选列表');
      this.topFilterList.find(x => x.fieldName === 'I_AUART').itemList = this.orderSelectData.map(x => ({ text: x.partTypeName, value: x.partTypeId }));
      let obj = {};
      this.orderSelectData.map(item => {
        obj[item.partTypeNo] = item.partTypeName;
      });
      this.orderTypeData = obj;
      // console.log(this.orderTypeData, '订单类型订单类型');
    },
    handlerSelectConfirm() {},
    removeRecordHandle() {},
    // 点击打印申请单
    async handleApplyPrint() {
      if (this.selectedRow.length) {
        this.printBtnLoading = true;
        // 获取公司信息
        let companyData = {};
        try {
          companyData = await queryCompanyInforById({
            owenrCode: getCompanyId()
          });
        } catch (err) {
          console.log(err, '获取公司信息失败');
        }

        // 税率不存在的情况下获取税率
        if (!this.tax) {
          let taxRes = await queryTex();
          if (taxRes.resultCode == 200) {
            this.tax = taxRes.data * 1;
          } else {
            this.tax = 0.13;
          }
        }

        // 获取打印数据
        let res = await queryOrderPrintData({
          VBELN: this.selectedRow[0].QVBELN
        });
        this.printBtnLoading = false;
        if (res.resultCode == 200) {
          // KWMENG 数量(需要转换)  NETWR 总价(单价需要除)  MATNR 配件代码 ARKTX 配件名称 还需要计算税额
          res.data.map(item => {
            item.KWMENG = parseFloat(item.KWMENG).toFixed(2);
            item.PER_PRICE = (item.NETWR / item.KWMENG).toFixed(2); // 单价

            let notaxAmount = item.NETWR / (1 + this.tax * 1);
            item.TAX_AMOUNT = (item.NETWR - notaxAmount).toFixed(2); // 税额
            item.NETWR = parseFloat(item.NETWR).toFixed(2);
            item.TAX = this.tax * 100 + '%';
          });
          companyData.data.orderNo = this.selectedRow[0].QVBELN;
          this.printData = {
            itemlist: res.data,
            companyData: companyData.data
          };
          this.$refs.print.EXCUTE_PRINT();
        }
      } else {
        notifyAction('请选择需要打印的单据', 'warning');
      }
    },

    closeHandler(val, type) {
      this.visibleArrival = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    handlePageClose() {
      this.$emit('close');
    },
    // 点击签收按钮
    handleSign() {
      if (this.selectedRow.length) {
        if (this.selectedRow[0].DVBELN) {
          this.selectBillId = this.selectedRow[0].ID || null;
          this.selectedBillNo = this.selectedRow[0].DVBELN;
          this.signOfVisible = true;
        } else {
          notifyAction('发货单号为空不能签收', 'warning');
        }
      } else {
        notifyAction('请选择需要签收的订单', 'warning');
      }
    }
  }
};
</script>

<style scoped>
.searchBtn {
  text-align: center;
  margin-bottom: 10px;
}
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
